package cn.lsh.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * UDF已经过时，hive推荐使用GenericUDF，该类支持更多的数据类型且效率更高
 */
public class TuoMin extends GenericUDF {
	Logger log = LoggerFactory.getLogger(TuoMin.class);

	@Override
	public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
		//初始化，可以进行参数校验，对象实例化等等，定义evaluate返回类型
		return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
	}

	@Override
	public Text evaluate(DeferredObject[] deferredObjects) throws HiveException {
		//业务逻辑
		if (deferredObjects.length != 1) {
			throw new UDFArgumentLengthException("UDF只支持一个入参");
		}
		log.info("入参类型：" + deferredObjects[0].get().getClass());
		String src = deferredObjects[0].get().toString();
		log.info("入参：" + src);
		StringBuilder newStr = new StringBuilder(src.charAt(0) + "");
		if (src.length() > 2) {
			for (int i = 1; i < src.length(); i++) {
				if (i == src.length() - 1) {
					newStr.append(src.charAt(i));
				} else {
					newStr.append("*");
				}
			}
		} else {
			newStr.append("*");
		}
		log.info("脱敏后姓名：" + newStr.toString());
		return new Text(newStr.toString());
	}

	@Override
	public String getDisplayString(String[] strings) {
		//显示函数的帮助信息
		return "姓名脱敏，只显示姓，如张**";
	}

	public static void main(String[] args) throws Exception {
		DeferredObject[] deferredObjects = new DeferredObject[] {new DeferredJavaObject("吴彦祖")};
		Text text = (Text) new TuoMin().evaluate(deferredObjects);
		System.out.println(text.toString());
	}
}
